<?php

namespace app\health\service;

use app\common\library\time\TimeHelper;
use app\health\model\MasterUser;
use Exception;
use GuzzleHttp\Client;
use think\Cache;
use think\Env;
use think\exception\ValidateException;

/**
 * 平安健康用户业务查询
 * @Author 张旭鹏
 * @DateTime 2023-07-04
 */
class EquityCenterService
{
    private const KEY = '8FF1CCE474FE02D3BB14C873F31C1EFE';

    private static function urlBase()
    {
        return Env::get('health.service_url', "http://healthpro.xinquanyu.top");
    }

    //作用：生成签名
    private static function getSign($Parameters, $key)
    {
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = self::formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在 string 后加入 KEY
        $String = $String . "&key=" . $key;
        // dump($String);
        //签名步骤三：MD5 加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($String);
        // halt($result_);
        return $result;
    }

    ///作用：格式化参数，签名过程需要使用
    private static function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 查询用户是否平安健康会员
     * @param [type] $mobile
     * @param [type] $masterUserId
     * @Author 张旭鹏
     * @DateTime 2023-07-04
     */
    public static function isPajkVip($mobile): ?int
    {
        try {
            $url        = self::urlBase() . '/index.php/api/ThirdUserCard/isOrder';
            $formParams = ['mobile' => $mobile, 'user_id' => MasterUser::getMasterUserId($mobile)];
            $cacheKey   = 'user_is_vip:' . md5(http_build_query($formParams));
            $isVip      = Cache::get($cacheKey);
            if ($isVip === false) {
                $sign     = self::getSign($formParams, self::KEY);
                $client   = new Client();
                $response = $client->post($url, [
                    'headers'     => [
                        'sign' => $sign
                    ],
                    'form_params' => $formParams
                ]);
                $data     = json_decode($response->getBody()->getContents(), true);
                $isVip    = $data['data']['is_order'];
                Cache::set($cacheKey, $isVip, 300);
            }
            return (int)$isVip;
        } catch (Exception $e) {
            return 0;
        }
    }

    /**
     * 判断订购那个业务
     * @param [type] $mobile
     * @param [type] $type 服务类型 1 问诊 3 挂号 4 二诊
     * @return array
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public static function isServer($mobile, $type)
    {
        try {
            $url        = self::urlBase() . '/index.php/api/ThirdUserCard/isServer';
            $formParams = ['mobile' => $mobile, 'type' => $type];
            $sign       = self::getSign($formParams, self::KEY);
            $client     = new Client();
            $response   = $client->post($url, [
                'headers'     => [
                    'sign' => $sign
                ],
                'form_params' => $formParams
            ]);
            $data       = json_decode($response->getBody()->getContents(), true);
            return $data['data'];
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * 创建年卡订单
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public static function orderAnnualCard($mobile, $masterUserId)
    {
        try {
            $url        = self::urlBase() . '/index.php/api/ThirdUserCard/order';
            $formParams = ['mobile' => $mobile, 'user_id' => $masterUserId];
            $sign       = self::getSign($formParams, self::KEY);
            $client     = new Client();
            $response   = $client->post($url, [
                'headers'     => [
                    'sign' => $sign
                ],
                'form_params' => $formParams
            ]);
            $data       = json_decode($response->getBody()->getContents(), true);
            return $data['data'];
        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * 年卡支付订单成功通知
     * @param [type] $orderNo
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public static function orderNotify($orderNo)
    {
        try {
            $url        = self::urlBase() . '/index.php/api/ThirdUserCard/notifyOrderStatus';
            $formParams = ['order_no' => $orderNo];
            $sign       = self::getSign($formParams, self::KEY);
            $client     = new Client();
            $response   = $client->post($url, [
                'headers'     => [
                    'sign' => $sign
                ],
                'form_params' => $formParams
            ]);
            $data       = json_decode($response->getBody()->getContents(), true);
            if (empty($data['result_code'])) {
                throw new Exception('请求失败');
            }
            return $data['code'] == 1;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 发送短信接口
     * @param [type] $mobile
     * @Author 张旭鹏
     * @DateTime 2023-07-06
     */
    public static function sendCode($mobile, $city, $zfCode)
    {
        $pid        = 2;
        $url        = 'http://cladmin.xinquanyu.top/index.php/api/PAJKmobile/getCode';
        $formParams = ['mobile' => $mobile, 'ip' => request()->ip(), 'pid' => $pid, 'city' => $city, 'zfCode' => $zfCode];
        try {
            $client   = new Client();
            $response = $client->post($url, [
                'form_params' => $formParams
            ]);
            $data     = json_decode($response->getBody()->getContents(), true);
            if (!isset($data['code'])) {
                throw new Exception('请求失败');
            }
            if ($data['code'] != 0) {
                throw new Exception($data['msg']);
            }
            return $data['data'];
        } catch (Exception $e) {
            if (!($e instanceof ValidateException)) {
                SystemNoticeService::develop('权益接口错误', "#### 验证码获取失败\n\n>获取手机验证码失败\n\n>接口地址:{$url}\n\n>请求参数:" . json_encode($formParams) . "\n\n>错误信息:" . $e->getMessage(), true);
            }
            return ['error_code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    /**
     * 业务办理
     * @param $mobile
     * @param $code
     * @param $zfCode
     * @param $city
     * @return array|true
     */
    public static function busHandle($mobile, $code, $zfCode, $city)
    {
        $pid        = 2;
        $url        = 'http://cladmin.xinquanyu.top/index.php/api/PAJKmobile/busHandleV2';
        $platform   = '鑫互助小程序';
        $formParams = [
            'mobile'   => $mobile,
            'code'     => $code,
            'url'      => '/pages/main/index/index',
            'zfCode'   => $zfCode,
            'pid'      => $pid,
            'platform' => $platform,
            'city'     => $city,
            'ip'       => request()->ip(),
        ];
        try {
            $client   = new Client();
            $response = $client->post($url, [
                'form_params' => $formParams
            ]);
            $data     = json_decode($response->getBody()->getContents(), true);
            if (!isset($data['code'])) {
                throw new Exception('请求失败');
            }
            if ($data['code'] != 0) {
                throw new Exception($data['msg']);
            }
            return true;
        } catch (Exception $e) {
            return ['error_code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    /**
     * 权益充值
     * @param $orderId
     * @param $type
     * @param $interests_type
     * @param $product_code
     * @param int|string $callbackId
     * @return true
     * @throws Exception
     */
    public static function recharge($orderId, $type, $interests_type, $product_code, $callbackId = 0): bool
    {
        $url        = self::urlBase() . '/index.php/api/ThirdUserCard/rechargeCard';
        $formParams = [
            'order_id'       => $orderId,
            'callback_id'    => $callbackId,
            'type'           => $type,
            'interests_type' => $interests_type,
            'product_code'   => $product_code,
        ];
        $sign       = self::getSign($formParams, self::KEY);
        $client     = new Client();
        $response   = $client->post($url, [
            'headers'     => [
                'sign' => $sign
            ],
            'form_params' => $formParams
        ]);
        $data       = json_decode($response->getBody()->getContents(), true);
        if (empty($data['code'])) {
            throw new Exception('充值失败,请联系客服', 1008);
        }
        if ((int)$data['code'] !== 1000) {
            throw new Exception($data['msg'], $data['code']);
        }
        return true;
    }

    /**
     * 获取平安健康token
     * @param $mobile
     * @return false|mixed
     */
    public static function getPajkToken($mobile)
    {
        try {
            $url        = self::urlBase() . '/index.php/api/ThirdUserCard/getToken';
            $formParams = ['mobile' => $mobile];
            $sign       = self::getSign($formParams, self::KEY);
            $client     = new Client();
            $response   = $client->post($url, [
                'headers'     => [
                    'sign' => $sign
                ],
                'form_params' => $formParams
            ]);
            $data       = json_decode($response->getBody()->getContents(), true);
            if ((int)$data['code'] !== 1000) {
                throw new Exception($data['msg']);
            }
            if (empty($data['token'])) {
                throw new Exception('token获取失败');
            }
            return ['token' => $data['token'], 'url' => $url, 'form_params' => $formParams];
        } catch (Exception $e) {
            return false;
        }
    }
}
